<template>
  <view class="mine-container" :style="{ height: `${windowHeight}px` }">
    <!--顶部个人信息栏-->
    <image class="back-img-box" :src="backImg"></image>
    <view class="header-section">
      <view class="enterprise"> {{ curTenant.enterName || '暂无' }} </view>
      <view class="flex padding justify-between">
        <view class="flex align-center">
          <image v-if="name" @click="handleToAvatar" :src="avatarImg" class="cu-avatar round" mode="widthFix"></image>
          <image v-if="!name" @click="handleToAvatar" :src="avatarImg_" class="cu-avatar round" mode="widthFix"></image>
          <view v-if="!name" @click="handleToLogin" class="login-tip font-18">点击登录</view>
          <view v-if="name" class="user-info font-14">
            <view class="u-title font-18">{{ name }}</view>
            <view class="u-title-fu">{{
              phone.substring(0, 3) + '****' + phone.substring(phone.length - 4)
              }}</view>
          </view>
        </view>
      </view>
    </view>
    <view class="wallet-box" :style="walletOuterBg">
      <view>
        <view class="money-text">{{ money }}</view>
        <view>钱包余额</view>
      </view>
      <view class="view-btn" @click="linkToWallet">查看</view>
    </view>
    <view class="content-section">
      <view class="menu-list font-15">
        <view class="list-cell list-cell-arrow" @click="handleDriver">
          <view class="menu-item-box">
            <view class="iconfont icon-renzheng menu-icon"></view>
            <view>司机认证</view>
          </view>
        </view>
        <view class="list-cell list-cell-arrow" @click="handleToSetting">
          <view class="menu-item-box">
            <view class="iconfont icon-cheliang menu-icon"></view>
            <view>我的车辆</view>
          </view>
        </view>
        <view v-if="false" class="list-cell list-cell-arrow" @click="handleToBankCard">
          <view class="menu-item-box">
            <view class="iconfont icon-yinhangka menu-icon"></view>
            <view>银行卡管理</view>
          </view>
        </view>
        <view class="list-cell list-cell-arrow" @click="handleToReminderRecord">
          <view class="menu-item-box">
            <image class="img-icon" :src="remindIcon" />
            <view>叫号提醒记录</view>
          </view>
        </view>
        <view class="list-cell list-cell-arrow" @click="switchEntery">
          <view class="menu-item-box">
            <image class="img-icon" :src="switchIcon" />
            <view>切换企业</view>
          </view>
        </view>
        <!-- <view class="list-cell list-cell-arrow" @click="handleToTransaction">
					<view class="menu-item-box">
						<view class="iconfont icon-jiaoyijilu menu-icon"></view>
						<view>交易记录</view>
					</view>
				</view> -->
        <view class="list-cell list-cell-arrow">
          <button open-type="contact"
            style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0;"></button>
          <view class="menu-item-box">
            <image class="img-icon" :src="feedbackIcon" />
            <view>在线反馈</view>
          </view>
        </view>

        <view class="list-cell" @click="handleLogout" v-if="name">
          <view class="menu-item-box">
            <view class="iconfont icon-tuichudenglu menu-icon"></view>
            <view>退出登录</view>
          </view>
        </view>
      </view>
    </view>
    <uni-popup class="tanantPop" type="dialog" ref="tenantDialog">
      <view class="tenantList">
        <text class="title">企业列表：</text>
        <view class="tenant-box">
          <view v-for="(item, index) in tenantList" :key="index" class="tenant-item" :class="{
              'active-item global-button-bg':
                curTenant && item.id === curTenant.id
            }" @click="handleItem(item)">
            <text class="cph">{{ item.enterName }}</text>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
  import storage from '@/utils/storage';
  import config from '@/config';
  import {
    getAccessToken,
    getTenantId,
    setTenantId,
    setOpenId,
    setToken,
    setDriverId
  } from '@/utils/auth';
  import { toast, showConfirm } from '@/utils/common';
  import { getTenentList, wxPhoneLogin, getOpenIdByCode } from '@/api/login.js';
  import { getWalletData } from '@/api/system/wallet.js';
  import { getDriving } from '@/api/me.js';
  import func from '@/utils/funlogin.js';
  export default {
    data() {
      return {
        name: null,
        money: '0.00',
        tenantList: [],
        curTenant: null,
        phone: uni.getStorageSync('sjxxData').mobile
      };
    },
    computed: {
      avatar() {
        return this.$store.state.user.avatar;
      },
      windowHeight() {
        return uni.getSystemInfoSync().windowHeight - 50;
      },
      backImg() {
        if (this.$store.state.user.curTypeColor == '#D22C2C') {
          return config.baseImgUrl + '/profile_red.png';
        } else if (this.$store.state.user.curTypeColor == '#409EFE') {
          return config.baseImgUrl + '/profile_blue.png';
        } else {
          return config.baseImgUrl + '/profile_blue.png';
        }
      },
      remindIcon() {
        return config.baseImgUrl + '/remind-icon.png';
      },
      switchIcon() {
        return config.baseImgUrl + '/switch-icon.png';
      },
      avatarImg_() {
        return config.baseImgUrl + '/user_.png';
      },
      avatarImg() {
        return config.baseImgUrl + '/user.png';
      },
      feedbackIcon() {
        return config.baseImgUrl + '/feedback-icon.png';
      },
      walletOuterBg() {
        return `background: url(${config.baseImgUrl}/wallet-bg.png) no-repeat;background-size: cover;`;
      }
    },
    onShow() {
      this.name = !!getAccessToken()
        ? uni.getStorageSync('sjxxData').driverName
        : null;
      this.$refs.tenantDialog?.close();
      if (getAccessToken()) {
        this.getWalletData();
        this.getTenentList();
      }
    },
    methods: {
      async getWalletData() {
        const res = await getWalletData();
        if (res?.code === 0) {
          this.money = ((res?.data?.balance || 0) / 100).toFixed(2);
        } else {
          toast(res.msg || '接口查询失败');
        }
      },
      async getTenentList() {
        const res = await getTenentList(this.phone);
        if (res.code === 0) {
          this.tenantList = res.data || [];
          this.curTenant = this.tenantList.find(
            (e) => e.id == getTenantId()
          );
        }
      },
      async handleItem(e) {
        wx.showLoading({
          title: '切换中...',
          mask: true
        });
        this.curTenant = e;
        setTenantId(this.curTenant.id);
        await this.loginWx();
        wx.hideLoading();
        this.getWalletData();
      },
      async loginWx() {
        const code = await func.wxLogin();
        const openid = await getOpenIdByCode(code);
        setOpenId(openid.data);
        const wxCode = await func.wxLogin();
        const data = {
          phoneCode: this.phone,
          loginCode: wxCode
        };
        const res = await wxPhoneLogin(data);
        if (res.code == 0) {
          setToken({
            accessToken: res.data.accessToken,
            refreshToken: res.data.refreshToken
          });
          setDriverId(res.data.userId);
          await this.getUserInfor();
        }
      },
      async getUserInfor() {
        try {
          const res = await getDriving();
          if (res.code == 0) {
            uni.setStorageSync('sjxxData', res.data || {});
            toast(`已成功切换企业为：\r\n ${this.curTenant.enterName}`);
            this.$refs.tenantDialog?.close();
          }
        } catch (e) {
          return false;
        }
      },
      handleToSetting() {
        let flag = this.isLogin();
        if (flag) this.$tab.navigateTo('/packageB/pages/mine/vehicle/vehicle');
      },
      handleToBankCard() {
        let flag = this.isLogin();
        if (flag)
          this.$tab.navigateTo('/packageB/pages/mine/bank-card/bank-card');
      },
      handleToReminderRecord() {
        let flag = this.isLogin();
        if (flag)
          this.$tab.navigateTo(
            '/packageB/pages/mine/reminder-records/reminderRecord'
          );
      },
      linkToWallet() {
        let flag = this.isLogin();
        if (flag) this.$tab.navigateTo('/packageB/pages/mine/my-wallet/myWallet');
      },
      switchEntery() {
        const flag = this.isLogin();
        if (!flag) {
          return;
        }
        this.$refs.tenantDialog?.open('bottom');
      },
      // handleToTransaction() {
      //   let flag = this.isLogin();
      //   if (flag)
      //     this.$tab.navigateTo('/packageB/pages/mine/transactions/transactions');
      // },
      handleToLogin() {
        this.$tab.reLaunch('/pages/login');
      },
      handleToAvatar() {
        // this.$tab.navigateTo('/pages/mine/avatar/index');
      },
      handleLogout() {
        this.$modal.confirm('确定注销并退出系统吗？').then(() => {
          this.$store.dispatch('LogOut').then(() => {
            this.$tab.reLaunch('/pages/login');
          });
        });
      },
      handleDriver() {
        let flag = this.isLogin();
        if (flag)
          this.$tab.navigateTo('/packageB/pages/mine/driver-auth/driver-auth');
      },
      handleJiaoLiuQun() {
        this.$modal.showToast('微信搜索 naidaguo 后，添加好友后拉你进技术交流群');
      },
      handleBuilding() {
        this.$modal.showToast('模块建设中~');
      },
      isLogin() {
        if (!this.name) {
          showConfirm('您当前处于未登录状态，是否去登录?').then((res) => {
            if (res.confirm) {
              uni.reLaunch({
                url: '/pages/login'
              });
            }
          });
          return false;
        }
        return true;
      }
    }
  };
</script>

<style lang="scss">
  page {
    background-color: #f5f6f7;
  }

  .mine-container {
    width: 100%;
    height: 100%;
    font-size: 30rpx;

    .back-img-box {
      width: 100vw;
      height: 200px;
      position: absolute;
      z-index: -1;
    }

    .header-section {
      padding: 15px 15px 15px 15px;
      color: white;

      .user-info {
        .u-title {
          font-size: 40upx;
          margin-bottom: 10rpx;
        }
      }

      .login-tip {
        font-size: 20upx;
        margin-left: 10px;
      }

      .cu-avatar {
        width: 140rpx !important;
        height: 140rpx !important;

        .icon {
          font-size: 40rpx;
        }
      }

      .user-info {
        margin-left: 15px;

        .u_title {
          height: 28px;
          line-height: 28px;
        }
      }
    }

    .wallet-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #573800;
      border-radius: 14.22rpx;
      margin: 0 26.67rpx 32rpx 26.67rpx;
      padding: 26.67rpx 26.67rpx 21.33rpx 26.67rpx;

      .money-text {
        font-size: 42.67rpx;
        font-weight: 600;
      }

      .view-btn {
        border-radius: 47rpx;
        padding: 8rpx 17.78rpx;
        background-color: #ffffff;
      }
    }

    .content-section {
      position: relative;
      font-size: 15px;

      .menu-list {
        padding-top: 10px;
        margin-top: 0px;

        .img-icon {
          width: 39.11rpx;
          height: 39.11rpx;
          margin-right: 14.22rpx;
        }
      }

      .mine-actions {
        margin: 15px 15px;
        padding: 20px 0px;
        border-radius: 8px;
        background-color: white;

        .action-item {
          .icon {
            font-size: 28px;
          }

          .text {
            display: block;
            font-size: 13px;
            margin: 8px 0px;
          }
        }
      }
    }
  }

  .tenantList {
    z-index: 99999;
    background: #fff;
    font-size: 30rpx;
    padding: 53.33rpx 17.78rpx;
    margin: 0 35.56rpx;
    border-radius: 8.89rpx;

    .tenant-box {
      max-height: 533.33rpx;
      overflow-y: auto;
    }

    .title {
      margin-bottom: 36rpx;
      display: block;
    }

    .tenant-item {
      text-align: center;
      height: 90rpx;
      line-height: 90rpx;
      border-radius: 8px;
      background: #d9d9d952;
      margin-bottom: 4rpx;
      color: #666;
      cursor: pointer;
      padding: 6rpx 0;
      margin-top: 17.78rpx;
    }

    .tenant-item:hover {
      background: #ececec;
    }
  }

  .active-item {
    color: #ffffff !important;
  }

  .enterprise {
    padding: 4px 10px;
    border-radius: 20px;
    background-color: #3097ff;
  }
</style>